package eu.ioc.factory;

import java.io.File;
import java.net.URLDecoder;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import stub.ioc.Student;

/**
 * 类厂
 * @author wzz
 *
 */
public class BeansFactory {
	Document xml = null;
	
	public BeansFactory(String path){
		SAXReader sr = new SAXReader();
		try {
			File file = new File(path); 
			if (!file.exists()) {
				System.err.println("file not found: "+path);
				return;
			}
			xml = sr.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public Object getBean(String id) {
		try {
			Element beanEle = BeanMaker.locateBean(xml, id);
			if (beanEle == null) {
				System.err.println("can't locate with id:"+id);
				return null;
			}
			String clazz = beanEle.attributeValue("class");
			Object instance = BeanMaker.createBean(clazz);
			for (Object beanEles : beanEle.selectNodes("property")) {
				Element proEle = (Element) beanEles;
				BeanMaker.setProperty(Class.forName(clazz), instance, proEle);
			}
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) throws Exception {
		BeansFactory fac = new BeansFactory(
				URLDecoder.decode(BeansFactory.class.getResource("/").getPath()+"beans.xml", "UTF-8"));
		Student stu = (Student) fac.getBean("default.student");
		System.out.println(stu.getStudent().getName());
		for (String s : stu.getObj())
			System.out.println(s);
		System.out.println(stu.getTime());
	}
}
